//
//  mySocketManager.m
//  mySocketLocalServer
//
//  Created by Radish on 16/3/14.
//  Copyright © 2016年 Radish. All rights reserved.
//

#import "mySocketManager.h"
#import "AsyncSocket.h"

@interface mySocketManager(){
    AsyncSocket *serverSocket;
}

@property (nonatomic, strong) NSMutableArray *clients;

@end

@implementation mySocketManager

-(instancetype)init{
    self = [super init];
    if (self) {
        serverSocket = [[AsyncSocket alloc]initWithDelegate:self];
    }
    return self;
}
-(NSMutableArray *)clients{
    if (!_clients) {
        _clients = [NSMutableArray array];
    }
    return _clients;
}
- (void) startLinkLocalSocket{
    NSError *error;
    [serverSocket acceptOnPort:12345 error:&error];
    if (!error) {
        NSLog(@"连接成功");
    }
}

#pragma mark asyncsocket delegate
-(void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket{
    NSLog(@"有新的客户端想连接到本地服务器 >>> %ld",[sock userData]);
    NSLog(@"私有变量serversocket >>>> %p 代理返回的sock >>>%p 客户端的socket >>> %p >>",serverSocket,sock,newSocket);
    //将客户端保存起来 如果保存会出现
    //RadishdeMacBook-Pro:~ Radish$ telnet 127.0.0.1 54321
    //Connected to localhost.
    //Connection closed by foreign host.
    [self.clients addObject:newSocket];
    //服务端的socket/serverSocket 只负责跟客户端的连接，因此发送数据，要用客户端发送数据
    [newSocket readDataWithTimeout:-1 tag:100];
}
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"服务端收到信息，有可读的数据进来了");
    NSString *message = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@ >>>> 客户端 socket >>> %p",message,sock);
    if ([message hasPrefix:@"iam:"]) {
        NSString *resposeToClient = @"恭喜你加入socket\n";
        [sock writeData:[resposeToClient dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:101];
    }
    else if ([message hasPrefix:@"msg:"]){
        //接收到 msg：开头的数据 找出另外一个客户端 给它发送数据
        for (AsyncSocket *reciveSocket in self.clients) {
            if (reciveSocket != sock) {
                [reciveSocket writeData:data withTimeout:-1 tag:tag];
                break;
            }
        }
    }
    else if([message containsString:@"quit"]){
        NSString *resposeToClient = @"( ^_^ )/~~拜拜 \n";
        [sock writeData:[resposeToClient dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:103];
    }
    else{
        [sock readDataWithTimeout:-1 tag:100];
    }
}
-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"服务端往客户端发送数据，写入数据完成，开始发送");
    NSLog(@"客户端 socket >>> %p",sock);
    if (tag == 103) {
        //断开连接
        [sock disconnect];
        //移除客户端
        [self.clients removeObject:sock];
    }
    else{
        [sock readDataWithTimeout:-1 tag:100];
    }
}



@end
